<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket 消息系统</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            display: flex;
            gap: 20px;
        }
        .left-panel {
            flex: 1;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .right-panel {
            flex: 2;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .connection-status {
            padding: 10px;
            margin-bottom: 20px;
            border-radius: 4px;
            text-align: center;
            font-weight: bold;
        }
        .connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .disconnected {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, textarea, select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        button {
            background-color: #007bff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        button:hover {
            background-color: #0056b3;
        }
        button:disabled {
            background-color: #6c757d;
            cursor: not-allowed;
        }
        .message-list {
            height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            background-color: #f9f9f9;
            border-radius: 4px;
        }
        .message-item {
            margin-bottom: 10px;
            padding: 8px;
            background: white;
            border-radius: 4px;
            border-left: 4px solid #007bff;
        }
        .dialog-list {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            background-color: #f9f9f9;
            border-radius: 4px;
        }
        .dialog-item {
            padding: 8px;
            margin-bottom: 5px;
            background: white;
            border-radius: 4px;
            cursor: pointer;
            border: 1px solid #ddd;
        }
        .dialog-item:hover {
            background-color: #e9ecef;
        }
        .dialog-item.active {
            background-color: #007bff;
            color: white;
        }
        .log-area {
            height: 200px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            background-color: #f8f9fa;
            font-family: monospace;
            font-size: 12px;
            border-radius: 4px;
        }
        .log-item {
            margin-bottom: 5px;
            padding: 2px 0;
        }
        .log-send {
            color: #007bff;
        }
        .log-receive {
            color: #28a745;
        }
        .log-error {
            color: #dc3545;
        }
    </style>
</head>
<body>
    <h1>WebSocket 消息系统</h1>
    
    <div class="connection-status" id="connectionStatus">
        未连接
    </div>
    
    <div class="container">
        <div class="left-panel">
            <h3>连接控制</h3>
            <div class="form-group">
                <label for="wsUrl">WebSocket URL:</label>
                <input type="text" id="wsUrl" value="ws://localhost:7081/ws/message" placeholder="WebSocket URL">
            </div>
            <div class="form-group">
                <label for="userId">用户ID:</label>
                <input type="number" id="userId" value="1" placeholder="用户ID">
            </div>
            <div class="form-group">
                <label for="token">Token:</label>
                <input type="text" id="token" value="93ad95081e3834159c916688f1632a49" placeholder="Token">
            </div>
            <button onclick="connect()" id="connectBtn">连接</button>
            <button onclick="disconnect()" id="disconnectBtn" disabled>断开连接</button>
            
            <h3>对话框列表</h3>
            <button onclick="getDialogList()" disabled id="getDialogBtn">获取对话框列表</button>
            <div class="dialog-list" id="dialogList">
                <div class="dialog-item">请先连接WebSocket</div>
            </div>
            
            <h3>操作日志</h3>
            <div class="log-area" id="logArea"></div>
        </div>
        
        <div class="right-panel">
            <h3>消息操作</h3>
            
            <div class="form-group">
                <label for="dialogId">对话框ID:</label>
                <input type="number" id="dialogId" placeholder="对话框ID (留空创建新对话)">
            </div>
            
            <div class="form-group">
                <label for="messageType">消息类型:</label>
                <select id="messageType">
                    <option value="1">文本消息</option>
                    <option value="2">图片消息</option>
                    <option value="3">文件消息</option>
                </select>
            </div>
            
            <div class="form-group">
                <label for="messageContent">消息内容:</label>
                <textarea id="messageContent" rows="3" placeholder="请输入消息内容"></textarea>
            </div>
            
            <div class="form-group">
                <label for="members">成员列表 (逗号分隔):</label>
                <input type="text" id="members" placeholder="agent_1,user_2" value="agent_1">
            </div>
            
            <button onclick="sendMessage()" disabled id="sendBtn">发送消息</button>
            <button onclick="getMessageList()" disabled id="getMsgBtn">获取消息列表</button>
            <button onclick="deleteDialog()" disabled id="delDialogBtn">删除对话框</button>
            <button onclick="testStream()" disabled id="testStreamBtn">测试流式输出</button>
            
            <h3>消息列表</h3>
            <div class="message-list" id="messageList">
                <div class="message-item">请先连接WebSocket并选择对话框</div>
            </div>

            <h3>AI流式事件演示</h3>
            <div class="form-group">
                <label>AI状态：</label>
                <div id="ai-status" style="color:#ff9800;font-weight:bold;min-height:24px;"></div>
            </div>
            <div class="form-group">
                <label>AI内容：</label>
                <div id="ai-content" style="background:#f3f3f3;min-height:40px;padding:8px;border-radius:4px;"></div>
            </div>
        </div>
    </div>

    <script>
        let ws = null;
        let currentDialogId = null;
        
        // 连接WebSocket
        function connect() {
            const url = document.getElementById('wsUrl').value;
            const userId = document.getElementById('userId').value;
            const token = document.getElementById('token').value;
            
            if (!url || !userId) {
                log('请输入WebSocket URL和用户ID', 'error');
                return;
            }
            
            try {
                ws = new WebSocket(url + '?token=' + token);
                
                ws.onopen = function(event) {
                    updateConnectionStatus(true);
                    log('WebSocket连接已建立', 'receive');
                    enableButtons(true);
                };
                
                ws.onmessage = function(event) {
                    log('收到消息: ' + event.data, 'receive');
                    handleMessage(event.data);
                };
                
                ws.onclose = function(event) {
                    updateConnectionStatus(false);
                    log('WebSocket连接已关闭', 'error');
                    enableButtons(false);
                };
                
                ws.onerror = function(error) {
                    log('WebSocket错误: ' + error, 'error');
                    updateConnectionStatus(false);
                    enableButtons(false);
                };
                
            } catch (error) {
                log('连接失败: ' + error.message, 'error');
            }
        }
        
        // 断开连接
        function disconnect() {
            if (ws) {
                ws.close();
                ws = null;
            }
        }
        
        // 更新连接状态
        function updateConnectionStatus(connected) {
            const status = document.getElementById('connectionStatus');
            const connectBtn = document.getElementById('connectBtn');
            const disconnectBtn = document.getElementById('disconnectBtn');
            
            if (connected) {
                status.textContent = '已连接';
                status.className = 'connection-status connected';
                connectBtn.disabled = true;
                disconnectBtn.disabled = false;
            } else {
                status.textContent = '未连接';
                status.className = 'connection-status disconnected';
                connectBtn.disabled = false;
                disconnectBtn.disabled = true;
            }
        }
        
        // 启用/禁用按钮
        function enableButtons(enable) {
            document.getElementById('getDialogBtn').disabled = !enable;
            document.getElementById('sendBtn').disabled = !enable;
            document.getElementById('getMsgBtn').disabled = !enable;
            document.getElementById('delDialogBtn').disabled = !enable;
            document.getElementById('testStreamBtn').disabled = !enable;
        }
        
        // 发送WebSocket消息
        function sendWebSocketMessage(action, data) {
            if (!ws || ws.readyState !== WebSocket.OPEN) {
                log('WebSocket未连接', 'error');
                return;
            }
            
            const message = {
                action: action,
                data: data
            };
            
            const messageStr = JSON.stringify(message);
            ws.send(messageStr);
            log('发送消息: ' + messageStr, 'send');
        }
        
        // 发送消息
        function sendMessage() {
            const dialogId = document.getElementById('dialogId').value;
            const type = document.getElementById('messageType').value;
            const content = document.getElementById('messageContent').value;
            const members = document.getElementById('members').value;
            
            if (!content.trim()) {
                log('请输入消息内容', 'error');
                return;
            }
            
            const data = {
                dialogId: dialogId ? parseInt(dialogId) : null,
                type: parseInt(type),
                content: content,
                members: members ? members.split(',').map(m => m.trim()) : []
            };
            
            sendWebSocketMessage('sendMessage', data);
        }
        
        // 获取消息列表
        function getMessageList() {
            const dialogId = document.getElementById('dialogId').value;
            if (!dialogId) {
                log('请先选择对话框', 'error');
                return;
            }
            
            const data = {
                dialogId: parseInt(dialogId),
                page: 1,
                pagesize: 20
            };
            
            sendWebSocketMessage('getMessageList', data);
        }
        
        // 获取对话框列表
        function getDialogList() {
            const data = {};
            
            sendWebSocketMessage('getDialogList', data);
        }
        
        // 删除对话框
        function deleteDialog() {
            const dialogId = document.getElementById('dialogId').value;
            if (!dialogId) {
                log('请先选择对话框', 'error');
                return;
            }
            
            const data = {
                dialogId: parseInt(dialogId)
            };
            
            sendWebSocketMessage('delDialog', data);
        }
        
        // 测试流式输出
        function testStream() {
            sendWebSocketMessage('testStream', {});
        }
        
        // 处理接收到的消息
        function handleMessage(data) {
            // 先判断是否为AI流式事件
            try {
                const aiJson = JSON.parse(data);
                if (aiJson && aiJson.event) {
                    if (aiJson.event === 'thinking') {
                        document.getElementById('ai-status').innerText = '思考中...';
                        document.getElementById('ai-content').innerText = '';
                    } else if (aiJson.event === 'answer') {
                        document.getElementById('ai-status').innerText = '已经为你找到结果';
                        document.getElementById('ai-content').innerText += aiJson.data;
                    } else if (aiJson.event === 'end') {
                        // 不做处理
                    }
                    return;
                }
            } catch (e) {}
            try {
                // 尝试解析JSON
                const jsonData = JSON.parse(data);
                
                // 根据消息类型处理
                if (Array.isArray(jsonData)) {
                    // 消息列表或对话框列表
                    if (jsonData.length > 0 && jsonData[0].hasOwnProperty('dialogId')) {
                        // 消息列表
                        displayMessageList(jsonData);
                    } else {
                        // 对话框列表
                        displayDialogList(jsonData);
                    }
                } else if (jsonData.hasOwnProperty('result')) {
                    // 删除对话框结果
                    log('删除对话框结果: ' + JSON.stringify(jsonData), 'receive');
                } else {
                    // 其他JSON响应
                    log('收到响应: ' + JSON.stringify(jsonData), 'receive');
                }
            } catch (e) {
                // 非JSON消息（如流式输出）
                log('收到文本: ' + data, 'receive');
            }
        }
        
        // 显示消息列表
        function displayMessageList(messages) {
            const messageList = document.getElementById('messageList');
            messageList.innerHTML = '';
            
            if (messages.length === 0) {
                messageList.innerHTML = '<div class="message-item">暂无消息</div>';
                return;
            }
            
            messages.forEach(message => {
                const messageDiv = document.createElement('div');
                messageDiv.className = 'message-item';
                messageDiv.innerHTML = `
                    <strong>ID: ${message.id}</strong><br>
                    <strong>发送者: ${message.senderId}</strong><br>
                    <strong>类型: ${message.type}</strong><br>
                    <strong>内容: ${message.content}</strong><br>
                    <strong>时间: ${new Date(message.createTime).toLocaleString()}</strong>
                `;
                messageList.appendChild(messageDiv);
            });
        }
        
        // 显示对话框列表
        function displayDialogList(dialogs) {
            const dialogList = document.getElementById('dialogList');
            dialogList.innerHTML = '';
            
            if (dialogs.length === 0) {
                dialogList.innerHTML = '<div class="dialog-item">暂无对话框</div>';
                return;
            }
            
            dialogs.forEach(dialog => {
                const dialogDiv = document.createElement('div');
                dialogDiv.className = 'dialog-item';
                dialogDiv.innerHTML = `
                    <strong>ID: ${dialog.id}</strong><br>
                    <strong>名称: ${dialog.name}</strong><br>
                    <strong>类型: ${dialog.type === 1 ? '单聊' : '群聊'}</strong>
                `;
                dialogDiv.onclick = function() {
                    // 移除其他active状态
                    document.querySelectorAll('.dialog-item').forEach(item => {
                        item.classList.remove('active');
                    });
                    // 添加active状态
                    dialogDiv.classList.add('active');
                    // 设置当前对话框ID
                    currentDialogId = dialog.id;
                    document.getElementById('dialogId').value = dialog.id;
                };
                dialogList.appendChild(dialogDiv);
            });
        }
        
        // 日志记录
        function log(message, type = 'receive') {
            const logArea = document.getElementById('logArea');
            const logItem = document.createElement('div');
            logItem.className = 'log-item log-' + type;
            logItem.textContent = new Date().toLocaleTimeString() + ': ' + message;
            logArea.appendChild(logItem);
            logArea.scrollTop = logArea.scrollHeight;
        }
        
        // 页面加载完成后的初始化
        window.onload = function() {
            log('页面加载完成，请连接WebSocket', 'receive');
        };
    </script>
</body>
</html> 